import { bindAuth } from '@/api/login'
import { kefuUrl } from '@/utils/costum'
import PsMessageBox from "@/components/message-box/index";
import PsMessage from "@/components/message/index";
import { invokeAPi } from '@/xz-fn'
import { userAppStore } from '@/stores/user'

export default {
  data () {
    return {
      bindLoading: false
    }
  },
  methods: {
    onBindAuth (params = {}, from = 'wx') {
      return new Promise((resolve, reject) => {
        this.bindLoading = true
        bindAuth(params).then(res => {
          const data = res.data || {}
          this.bindLoading = false
          if (data.need_merge) {
            const isWx = from === 'wx'
            const msg = isWx
              ? '该账号已注册登录过，不支持绑定'
              : '当前绑定的手机号码已存在，请更换手机号码'
            PsMessage({
              message: msg,
              customClass: 'wrap'
            })
            reject(data)
          } else {
            this.completeBind()
            resolve(void 0)
          }
        }).catch(err => {
          this.bindLoading = false
          reject(err)
        })
      })
    },
    /**
     * 绑定完成
     * @param {Boolean} isAgainLogin
     */
    completeBind ({ isAgainLogin }: any = {}) {
      this.$emit('completeBind')
      if (isAgainLogin) {
        // 需要退出重新登录
        userAppStore().logout()
        // 需重新登录打开登录方式是绑定类型
        userAppStore().login()
        PsMessage({ message: '绑定成功，请重新登录', iconClass: 'success' })
      } else {
        // 更新绑定信息
        userAppStore().getUserInfo()
        PsMessage({ message: '绑定成功', iconClass: 'success' })
      }
      invokeAPi('fq_update_vip_info')
    }
  }
}
